mui.init();
var storage = window.localStorage;
var auths = null;
var appid = 'kou72um0ioak1kubrz0klwx8a7s3l261mgt54vbyotnblnby';
var appkey = 'o56bexx1vr522x7ygfkvi7efvbhhmo6x2oaf3txb75wi2509';
AV.initialize(appid, appkey);
var Recommendation = AV.Object.extend('Recommendation');

var load_rec = function(recall) {
	var rec_query = new AV.Query(Recommendation);
	var user = AV.User.current();
	if (user) {
		rec_query.equalTo('user', user);
		rec_query.include('topic');
		rec_query.include('frame');
		rec_query.descending('createdAt');
		rec_query.find().then(function(eles) {
			if (eles.length == 0) {
				mui('#hint')[0].style.display = "block";
			}
			var rec_dict = {}; //for check
			var rec_array = []; //for render
			for (var i = 0; i < eles.length; i++) {
				var frame = eles[i].get('frame');
				var topic = eles[i].get('topic');
				if (!frame) {continue;}
				var meta_data = JSON.parse(frame.get('metaDataV2'));
				var content = meta_data.content;
				var imgs = [];
				var video_covers = [];
				for (var j = 0; j < content.length; j++) {
					if (content[j].type == 'photo' || content[j].type == 'gif') {
						var img_url = content[j].upyunUrl;
						imgs.push(img_url);
					} else if (content[j].type == 'video') {
						var img_url = content[j].coverUrl;
						video_covers.push(img_url);
					}
				}
				var cover = frame.get('coverUrl');
				if (cover == null || cover == undefined || cover == '') {
					if (imgs.length > 0) {
						cover = imgs[0];
					} else if (video_covers.length > 0) {
						cover = video_covers[0];
					}
				}

				rec_dict[frame.id] = {
					'cover': cover,
					'topic_name': topic.get('name'),
					'frame_name': frame.get('head'),
					'author': frame.get('author'),
					'avatar': meta_data.avatarUrl,
				};
				rec_array.push({
					'frame_id': frame.id,
					'cover': cover,
					'topic_name': topic.get('name'),
					'frame_name': frame.get('head'),
					'author': frame.get('author'),
					'avatar': meta_data.avatarUrl,
				});
			}
			storage['rec_dict'] = JSON.stringify(rec_dict);
			storage['rec_array'] = JSON.stringify(rec_array);
			if (recall) {
				recall();
			}
		}, function(error) {

		});
	} else {
		console.log('load: no user');
	}
};

var render_rec = function() {
	mui('#login')[0].style.display = 'none';
	mui('#collect')[0].style.display = 'block';
	if ('rec_array' in storage) {
		var rec_array = JSON.parse(storage['rec_array']);
		mui('#collect .recs-box')[0].innerHTML = '';
		for (var i = 0; i < rec_array.length; i++) {
			var rec_html = template('rec-tpl', rec_array[i]);
			var new_ele = document.createElement('div');
			new_ele.innerHTML = rec_html;
			mui('#collect .recs-box')[0].appendChild(new_ele);
		}
		load_rec();
	} else {
		console.log('render: no storage')
		load_rec(render_rec);
	}
};

mui.plusReady(function() {
	plus.oauth.getServices(function(services) {
		auths = services;
		var user = AV.User.current();
		if (user) {
			mui('#collect')[0].style.display = 'block';
			render_rec();
		} else {
			for (var i = 0; i < auths.length; i++) {
				if (auths[i].description == "新浪微博") {
					mui("#share-weibo-btn")[0].setAttribute("data-id", i);
				};
				if (auths[i].description == "微信") {
					mui("#share-wechat-btn")[0].setAttribute("data-id", i);
				};
				if (auths[i].description == "QQ") {
					mui("#share-qq-btn")[0].setAttribute("data-id", i);
				};
			};
			mui('#login')[0].style.display = 'block';
		}
	}, function(e) {
		alert("获取分享服务列表失败：" + e.message + " - " + e.code);
	});

	plus.webview.currentWebview().addEventListener("show", function(e) {
		if (storage['var_login_status_changed'] == 'true') {
			storage['var_login_status_changed'] = false;
			window.location.href = window.location.href;
			return;
		}

		var user = AV.User.current();
		if (user) {
			mui('#login')[0].style.display = 'none';
			mui('#collect')[0].style.display = 'block';
			load_rec(render_rec);
		} else {
			mui('#login')[0].style.display = 'block';
			mui('#collect')[0].style.display = 'none';
			mui('#collect .recs-box')[0].innerHTML = '';
		}
	}, false);

	//设定状态栏样式
	if (plus.navigator.isImmersedStatusbar() && mui.os.ios) {
		document.getElementById("bar-cover").style.display = 'block';
		document.getElementById("bar-cover").style.backgroundImage = "";
	}
	if (plus.navigator.isImmersedStatusbar() && mui.os.android) {
		document.getElementById("bar-cover").style.display = 'block';
		document.getElementById("bar-cover").style.backgroundColor = "";
	}

});

var oauth = function(type) {
	if (auths) {
		type = parseInt(type);
		var auth = auths[type];
		if (true) {
			console.log(auth.description + "准备登录...");
			auth.login(function() {
				plus.nativeUI.closeWaiting();
				//DQ：微信的问题是iOS打包的oauth无法取出unionid，但是安卓的可以……
				var auth_data = auth.authResult;
				if (auth.description == "微信") {
					console.log("微信登录成功：" + JSON.stringify(auth));
					AV.User._logInWith('weixin', {
						'authData': {
							'openid': auth_data.openid,
							'access_token': auth_data.access_token,
							'expiration_in': auth_data.expires_in,
						},
						'success': function(user) {
							storage['var_login_status_changed'] = true;
							window.location.href = window.location.href;
						},
						'error': function(user, error) {
							mui.toast(error.message);
						}
					});
				} else if (auth.description == "QQ") {
					console.log("QQ登录成功：" + JSON.stringify(auth_data));
					AV.User._logInWith('qq', {
						'authData': {
							'openid': auth_data.openid,
							'access_token': auth_data.access_token,
							'expiration_in': auth_data.expires_in,
						},
						'success': function(user) {
							storage['var_login_status_changed'] = true;
							window.location.href = window.location.href;
						},
						'error': function(user, error) {
							mui.toast(error.message);
						}
					});
				} else if (auth.description == "新浪微博") {
					console.log("微博登录成功：" + JSON.stringify(auth_data));
					console.log(JSON.stringify(auth.userInfo));
					//DQ：两个平台取出的key竟然不一样……
					if (mui.os.ios) {
						var token = auth_data.access_token
						var expires_time = auth_data.expires_in
					} else {
						var token = auth_data.token;
						var expires_time = auth_data.expires_time;
					}
					AV.User._logInWith('weibo', {
						'authData': {
							'uid': auth_data.uid,
							'access_token': token,
							'expiration_in': expires_time,
						},
						'success': function(user) {
							storage['var_login_status_changed'] = true;
							window.location.href = window.location.href;
						},
						'error': function(user, error) {
							mui.toast(error.message);
						}
					});
				}
			}, function(e) {
				plus.nativeUI.closeWaiting();
				mui.toast(e.message+" - "+e.code);
				//oauth failed
			});
		} else {
			//already has authResult
			var auth_data = auth.authResult;
			if (auth.description == "微信") {
				AV.User._logInWith('weixin', {
					'authData': {
						'openid': auth_data.unionid,
						'access_token': auth_data.access_token,
						'expiration_in': auth_data.expires_in,
					},
					'success': function(user) {
						render_rec();
					},
					'error': function(error) {
						console.log(JSON.stringify(error));
					}
				});
			} else if (auth.description == "QQ") {
				AV.User._logInWith('qq', {
					'authData': {
						'openid': auth_data.openid,
						'access_token': auth_data.access_token,
						'expiration_in': auth_data.expires_in,
					},
					'success': function(user) {
						render_rec();
					},
					'error': function(error) {
						console.log('error qq');
					}
				});
			} else if (auth.description == "新浪微博") {
				AV.User._logInWith('weibo', {
					'authData': {
						'uid': auth_data.uid,
						'access_token': auth_data.token,
						'expiration_in': auth_data.expires_time,
					},
					'success': function(user) {
						render_rec();
					},
					'error': function(error) {
						console.log('error weibo');
					}
				});
			}
		}
	} else {
		//no auth
		mui.toast("没有第三方登陆平台");
	}
};

mui('#login .auth').on('tap', 'img', function() {
	plus.nativeUI.showWaiting();
	oauth(this.getAttribute('data-id'));
});

mui('#collect').on('tap', '.rec', function() {
	var fid = this.getAttribute('data-id');
	mui.openWindow({
		id: 'frame',
		url: 'frame.html',
		styles: {
			top: 0,
			bottom: 0,
			bounce: 'vertical',
		},
		extras: {
			frame_id: fid,
		},
		show: {
			autoShow: true,
			aniShow: 'pop-in',
			duration: 300,
		},
		waiting: {
			autoShow: false,
		}
	});
});